import pymongo
import requests

class AiQiYi:
    def __init__(self):
        self.client_mongo = pymongo.MongoClient(host="localhost", port=27017)
        self.db = self.client_mongo["py_spider"]['movie_list']
        self.headers = {
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
        }
        self.url = "https://pcw-api.iqiyi.com/search/recommend/list"
        self.params = {
            "channel_id": "2",
            "data_type": "1",
            "mode": "11",
            "page_id": "2",
            "ret_num": "48",
            "session": "507d98561edaed51dcefb64c9e1f7011",
            "three_category_id": "15;must"
        }


    def __del__(self):
        self.client_mongo.close()
    def get_movie_info(self, params):
        response = requests.get(url=self.url, headers=self.headers, params=params).json()
        return response

    def parse_movie_info(self, response):
        movie_list = response["data"]["list"]
        save_movie_list = list()
        for movie in movie_list:
            item = dict()
            item['title'] = movie['title']
            item['playUrl'] = movie['playUrl']
            item['description'] = movie['description']
            save_movie_list.append(item)

        self.save_to_mongo(save_movie_list)
    def save_to_mongo(self, movie_list:list):
        self.db.insert_many(movie_list)
        print("插入数据成功：", movie_list)


    def main(self):
        for page in range(1, 5):
            params = {
                "channel_id": "2",
                "data_type": "1",
                "mode": "11",
                "page_id": page,
                "ret_num": "48",
                "session": "507d98561edaed51dcefb64c9e1f7011",
                "three_category_id": "15;must"
            }

            response = self.get_movie_info(params)
            self.parse_movie_info(response)


# url = "https://pcw-api.iqiyi.com/search/recommend/list"
# params = {
#     "channel_id": "2",
#     "data_type": "1",
#     "mode": "11",
#     "page_id": "2",
#     "ret_num": "48",
#     "session": "507d98561edaed51dcefb64c9e1f7011",
#     "three_category_id": "15;must"
# }
if __name__ == '__main__':
    aqy_movie = AiQiYi()
    aqy_movie.main()
